package com.charity.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.charity.domain.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;

import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Update;

@Mapper
public interface UserMapper extends BaseMapper<User> {
    /**
     * 插入用户
     * @param user 用户信息
     * @return 影响行数
     */
    @Insert("INSERT INTO charity_user (username, password, email, nickname, avatar, user_type, create_time, update_time) VALUES (#{username}, #{password}, #{email}, #{nickname}, #{avatar}, #{userType}, #{createTime}, #{updateTime})")
    int insert(User user);

    /**
     * 根据用户名查询用户
     * @param username 用户名
     * @return 用户信息
     */
    @Select("SELECT * FROM charity_user WHERE username = #{username}")
    User selectByUsername(@Param("username") String username);

       /**
     * 根据用户名查询管理员
     * @param username 用户名
     * @return 用户信息
     */
    @Select("SELECT * FROM charity_user WHERE username = #{username} and user_type=1")
    User selectAdminByUsername(@Param("username") String username);

    /**
     * 根据邮箱查询用户
     * @param email 邮箱
     * @return 用户信息
     */
    @Select("SELECT * FROM charity_user WHERE email = #{email}")
    User selectByEmail(@Param("email") String email);

    /**
     * 更新用户信息
     * @param user 用户信息
     * @return 影响行数
     */
    @Update("UPDATE charity_user SET username = #{username}, password = #{password}, email = #{email}, nickname = #{nickname}, avatar = #{avatar}, user_type = #{userType}, update_time = #{updateTime} WHERE id = #{id}")
    int updateById(User user);

    /**
     * 获取用户列表总数
     * @param username 用户名（可选）
     * @param userType 用户类型（可选）
     * @return 总数
     */
    @Select("<script>SELECT COUNT(*) FROM charity_user WHERE 1=1 "
            + "<if test='username != null and username != \"\"'>AND username LIKE CONCAT('%', #{username}, '%')</if>"
            + "<if test='userType != null'>AND user_type = #{userType}</if></script>")
    int selectCount(@Param("username") String username, @Param("userType") Integer userType);

    /**
     * 获取用户列表
     * @param offset 偏移量
     * @param size 每页大小
     * @param username 用户名（可选）
     * @param userType 用户类型（可选）
     * @return 用户列表
     */
    @Select("<script>SELECT * FROM charity_user WHERE 1=1 "
            + "<if test='username != null and username != \"\"'>AND username LIKE CONCAT('%', #{username}, '%')</if>"
            + "<if test='userType != null'>AND user_type = #{userType}</if>"
            + " LIMIT #{offset}, #{size}</script>")
    List<User> selectList(@Param("offset") int offset, @Param("size") int size,
                         @Param("username") String username, @Param("userType") Integer userType);
}